package org.qiuqiu.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class CodeImageUtil {
	public static String sendImage(HttpServletResponse resp, HttpServletRequest req) throws Exception{
		int width = 85;
		int height = 35;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width, height);
		g.setColor(Color.WHITE);
		g.fillRect(1, 1, width-2, height-2);
		g.setFont(new Font("微软雅黑", Font.BOLD, 25));
		
		String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		// sb存放生成的验证码字符串
		StringBuffer sb = new StringBuffer();
		// 生成验证码
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			int index = random.nextInt(data.length());
			String str = data.substring(index, index+1);
			g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
			g.drawString(str, 20*i+5, 25);
			sb.append(str);
		}
		
		//干扰线
		for(int i = 0 ; i < 10 ; i ++){
			//设置随机颜色
			g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
			//随机画直线
			g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
		}
		req.getSession().setAttribute("code", sb.toString());
		resp.setContentType("image/jpeg");
		ImageIO.write(image, "jpg", resp.getOutputStream());
		return sb.toString();
	}
}
